<?php

namespace App\Http\Controllers\api;

use App\Http\Controllers\Controller;
use App\Models\product\ProductModel;
use App\Models\users\UsersModel;
use App\Models\users\UsersNewModel;
use App\Service\users\UsersService;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Validator;
use lxs\api\ApiResponse;

class AgentController extends Controller
{

    /**
     * 获取代理商信息
     */
    public function getAgentInfo(): JsonResponse
    {
        $data = request()->data;

        $validator = Validator::make($data, [
            'mobile' => ['required', 'regex:/^1[34578]\d{9}$/'],
            'product_title' => ['required'],
            'popularize_id' => ['required'],
        ], [
            'mobile.required' => '请填写手机号码',
            'mobile.regex' => '手机号码格式不正确',
            'product_title.required' => '请填写商品标题',
            'popularize_id.required' => '请填写推广ID',
        ]);

        if ($validator->fails()) {
            return ApiResponse::apiResponseData(400, $validator->errors()->first());
        }

        // 获取代理商信息
        $agentInfo = UsersNewModel::rightJoin('users', 'users.id', '=', 'users_new.uid')
            ->select('users.*')
            ->where('users_new.mobile', $data['mobile'])
            ->first();

        if (!$agentInfo) {
            return ApiResponse::apiResponseData(400, '该手机号码未注册为代理商');
        }

        $product = ProductModel::rightJoin('product_son', 'product_son.product_id', '=', 'product.id')
            ->select('product_son.id')
            ->where('product_son.popularize_id', $data['popularize_id'])
            ->where('product_title', $data['product_title'])
            ->first();

        return ApiResponse::apiResponseData(200, '获取代理商信息和pro成功', [
            'unique' => $agentInfo->unique_id,
            'pro' => $product ? $product->id : 0,
        ]);

    }

}
